<template>
  <div class="add-todo-section">
    <textarea
      class="todo-input"
      placeholder="添加你的待办事项..."
      v-model="newTodoText"
      @keyup.enter="addTodo"
      rows="1"
      ref="todoInput"
    ></textarea>

    <div class="category-select" @click.stop="toggleCategoryDropdown">
      <div class="selected-tags">
        <template v-if="selectedCategories.length > 0">
          <div v-for="cat in selectedCategories" :key="cat.id" class="selected-tag">
            <span class="tag-name">{{ cat.name }}</span>
            <span class="tag-remove" @click.stop="removeSelectedCategory(cat)">×</span>
          </div>
        </template>
        <span v-else class="placeholder">选择标签</span>
      </div>
      <div class="dropdown-icon">▼</div>

      <div class="category-dropdown" v-if="showCategoryDropdown">
        <div
          v-for="category in localCategories"
          :key="category.id"
          class="category-item"
          @click.stop="toggleCategory(category)"
          :class="{ 'category-selected': isCategorySelected(category) }"
        >
          <span class="checkbox">
            <span v-if="isCategorySelected(category)" class="checkbox-inner">✓</span>
          </span>
          <span class="category-name">{{ category.name }}</span>
        </div>
      </div>
    </div>

    <button class="add-btn" @click="addTodo">添加待办</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, inject, watch, computed } from 'vue'
import { createTodo } from '@/api/todo'
import { getAllLabels } from '@/api/label'

// 从父组件注入方法
const fetchTodos = inject('fetchTodos', () => {})
const addTodoFn = inject('addTodo', null)
const injectedCategories = inject('categories', ref([]))

// 本地状态
const newTodoText = ref('')
const selectedCategories = ref([]) // 改为数组，支持多选
const showCategoryDropdown = ref(false)
const localCategories = ref([]) // 本地维护的标签列表

const todoInput = ref(null)

// 监听父组件注入的 categories 变化
watch(
  injectedCategories,
  (newCategories) => {
    // 保存当前选中的标签ID列表
    const currentSelectedIds = selectedCategories.value.map((cat) => cat.id)

    // 将注入的标签数据更新到本地
    localCategories.value = newCategories.map((category) => ({
      id: category.id,
      name: category.name,
      color: category.color || '#4361ee',
      order: category.order || 0,
    }))

    // 根据ID找到更新后的标签对象
    if (currentSelectedIds.length > 0) {
      selectedCategories.value = currentSelectedIds
        .map((id) => localCategories.value.find((cat) => cat.id === id))
        .filter((cat) => cat) // 过滤掉可能不存在的标签
    }

    // 如果没有选中的标签，默认不再选择任何标签
  },
  { immediate: true, deep: true },
)

const toggleCategoryDropdown = async (event) => {
  event.stopPropagation()
  showCategoryDropdown.value = !showCategoryDropdown.value

  // 当打开下拉菜单时，立即刷新标签数据
  if (showCategoryDropdown.value) {
    await initLabels()
  }
}

// 检查标签是否已选中
const isCategorySelected = (category) => {
  return selectedCategories.value.some((cat) => cat.id === category.id)
}

// 切换标签选中状态
const toggleCategory = (category) => {
  if (isCategorySelected(category)) {
    // 如果已选中，则移除
    removeSelectedCategory(category)
  } else {
    // 如果未选中，则添加
    selectedCategories.value.push(category)
  }
}

// 移除已选中的标签
const removeSelectedCategory = (category) => {
  selectedCategories.value = selectedCategories.value.filter((cat) => cat.id !== category.id)
}

// 获取选中标签的ID数组
const selectedCategoryIds = computed(() => {
  return selectedCategories.value.map((cat) => cat.id)
})

const addTodo = async () => {
  if (!newTodoText.value.trim() || selectedCategories.value.length === 0) {
    return
  }

  // 使用注入的addTodo函数(如果有)
  if (addTodoFn) {
    const success = await addTodoFn(newTodoText.value, selectedCategoryIds.value)
    if (success) {
      newTodoText.value = ''
      selectedCategories.value = []
      await initLabels()
      window.dispatchEvent(new Event('refresh-todo-list'))
    }
    return
  }

  // 回退到本地逻辑
  try {
    const result = await createTodo({
      content: newTodoText.value,
      labels: selectedCategoryIds.value,
    })

    if (result.success) {
      await fetchTodos()
      await initLabels()
      newTodoText.value = ''
      selectedCategories.value = []
      window.dispatchEvent(new Event('refresh-todo-list'))
    }
  } catch (error) {
    console.error('添加待办事项失败:', error)
  }
}

const handleClickOutside = () => {
  showCategoryDropdown.value = false
}

// 初始化标签数据
const initLabels = async () => {
  try {
    const result = await getAllLabels()
    if (result.success) {
      const currentSelectedIds = selectedCategories.value.map((cat) => cat.id)

      localCategories.value = result.data.map((label) => ({
        id: label.id,
        name: label.name,
        color: '#4361ee',
        order: 0,
      }))

      if (currentSelectedIds.length > 0) {
        selectedCategories.value = currentSelectedIds
          .map((id) => localCategories.value.find((cat) => cat.id === id))
          .filter((cat) => cat)
      }
    }
  } catch (error) {
    console.error('获取标签数据失败:', error)
  }
}

// 自动调整文本框高度的函数
const adjustTextareaHeight = () => {
  const textarea = todoInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = textarea.scrollHeight + 'px'
  }
}

// 监听输入内容变化
watch(newTodoText, () => {
  adjustTextareaHeight()
})

onMounted(() => {
  window.addEventListener('click', handleClickOutside)

  // 监听全局刷新事件，用于更新标签列表
  window.addEventListener('refresh-todo-list', async () => {
    await initLabels()
  })

  // 初始化标签数据
  initLabels()

  adjustTextareaHeight()
})

onUnmounted(() => {
  window.removeEventListener('click', handleClickOutside)
  window.removeEventListener('refresh-todo-list', () => {})
})
</script>

<style scoped>
.add-todo-section {
  margin-bottom: 40px;
}

.todo-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #d2d2d7;
  border-radius: 50px;
  font-size: 14px;
  margin-bottom: 15px;
  transition: all 0.3s;
  resize: none; /* 禁用手动调整大小 */
  overflow: hidden; /* 隐藏滚动条 */
  min-height: 45px; /* 设置最小高度 */
  line-height: 1.5; /* 设置行高 */
  font-family: inherit; /* 继承字体 */
}

.todo-input:focus {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

/* 当文本框高度增加时，调整圆角 */
.todo-input[style*='height'] {
  border-radius: 20px;
}

.category-select {
  position: relative;
  padding: 12px 15px;
  border: 1px solid #d2d2d7;
  border-radius: 15px;
  font-size: 14px;
  margin-bottom: 15px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 45px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
  gap: 6px;
}

.selected-tag {
  display: flex;
  align-items: center;
  background-color: #f0f2ff;
  border-radius: 20px;
  padding: 4px 10px;
  font-size: 12px;
}

.tag-name {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag-remove {
  margin-left: 5px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  border-radius: 50%;
}

.tag-remove:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

.placeholder {
  color: #86868b;
}

.dropdown-icon {
  font-size: 10px;
  color: #86868b;
  margin-left: 8px;
}

.category-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background-color: #ffffff;
  border: 1px solid #d2d2d7;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
  margin-top: 5px;
}

.category-item {
  padding: 10px 15px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
}

.category-item:hover {
  background-color: #f5f5f7;
}

.category-selected {
  background-color: #f0f2ff;
}

.checkbox {
  width: 18px;
  height: 18px;
  border-radius: 4px;
  border: 1px solid #d2d2d7;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-selected .checkbox {
  background-color: #4361ee;
  border-color: #4361ee;
}

.checkbox-inner {
  color: white;
  font-size: 12px;
}

.category-name {
  flex: 1;
}

.add-btn {
  width: 100%;
  padding: 12px 15px;
  background-color: #4361ee;
  color: white;
  border: none;
  border-radius: 50px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.add-btn:hover {
  background-color: #3a56d4;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(67, 97, 238, 0.3);
}
</style>
